package com.weidong.mybbs.interceptor;

import com.alibaba.fastjson.JSON;
import com.weidong.mybbs.annotation.SkipAuthValid;
import com.weidong.mybbs.service.AuthService;
import com.weidong.mybbs.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登陆拦截器
 */
@Component
public class RequireLoginInterceptor implements HandlerInterceptor {


    @Autowired
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sessionId = authService.getSessionId(request);
        HandlerMethod method = (HandlerMethod)handler;
        if (!method.hasMethodAnnotation(SkipAuthValid.class)){
            if (!authService.validLogin(sessionId)){
                if (!method.hasMethodAnnotation(ResponseBody.class)){
                    //获取类注解
                    if (method.getBeanType().getAnnotation(RestController.class) == null){
                        response.sendRedirect("/auth/login");
                        return false;
                    }
                }
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(AjaxResult.error(4000,"未登录")));
                writer.close();
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
        }
        return true;
    }
}
